import React, { useCallback, useEffect, useRef, useState } from 'react'
import { Switch, Route, Redirect } from 'react-router-dom';
import { connect } from "react-redux";

import { Card, Table } from 'antd';

import WebsocketHeartbeatJs from "@/plugins/heartbeat"

function List(props) {

    let [loading, setLoading] = useState(true)
    let [data, setData] = useState([])

    useEffect(() => {
        const url = "ws://10.3.144.89:1088/getInfo";
        let firstHeartbeat = true;
        let websocketHeartbeatJs = new WebsocketHeartbeatJs({
            url: url,
            pingTimeout: 10000,
            pongTimeout: 8000,
            reconnectTimeout: 8000
        });
        websocketHeartbeatJs.onopen = function () {
            console.log('%c 连接成功', "color:#f84");
            console.log(`%c 发送信息: ${props?.user.username}`, "color:#f84");
            setInterval(() => {
                websocketHeartbeatJs.send(props?.user.username);
            }, 1000)
            setTimeout(() => {
                console.log('等待' + websocketHeartbeatJs.opts.pingTimeout + '毫秒将发送请求->' + websocketHeartbeatJs.opts.pingMsg);
            }, 1500);
        }
        websocketHeartbeatJs.onmessage = function (e) {
            // console.log('%c' + e.data, "color:#f84");
            let json = JSON.parse(e.data);
            setData(json)
            setLoading(false)
            if (e.data == websocketHeartbeatJs.opts.pingMsg && firstHeartbeat) {
                setTimeout(() => {
                    console.log('关闭您的网络,等待 ' + websocketHeartbeatJs.opts.pingTimeout + websocketHeartbeatJs.opts.pongTimeout + '毫秒,websocket 将重连');
                }, 1500);
                firstHeartbeat = false;
            }
        }
        websocketHeartbeatJs.onreconnect = function () {
            console.log('%c 重连中...提示: 如果你的网络关闭,请打开你的网络,重连将会成功', "color:#f84");
        }
    }, [])

    const columns = [
        {
            title: '',
            dataIndex: 'name',
        }, {
            title: '',
            dataIndex: 'value',
        }
    ]

    return (
        <Card gutter={20}>
            <Table
                loading={loading}
                rowKey={row => row["name"]}
                columns={columns}
                dataSource={data}
                scroll={{ y: 'calc(100vh - 300px)' }}
                size="small"
                pagination={false}
            />
        </Card>
    )
}
export default connect(
    state => ({ user: state.user.userInfo }),
    dispatch => ({})
)(List)